using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ShopForWeb.Dto.ViewModels;

namespace ShopForWeb.UI.Filters;

public class UserInfoFiler : Attribute, IResultFilter
{
  public void OnResultExecuted(ResultExecutedContext context)
  {
  }

  public void OnResultExecuting(ResultExecutingContext context)
  {
    var controller = context.Controller as Controller;
    var user = controller!.HttpContext.User;
    if (user.Identity?.IsAuthenticated ?? false)
    {
      controller.ViewBag.User = new UserViewModels()
      {
        UserID = Convert.ToInt32(user.FindFirst(ClaimTypes.Sid)?.Value),
        Name = user.FindFirst(ClaimTypes.Name)?.Value ?? ""
      };
    }
    else
      controller!.ViewBag.User = null;

  }
}
